var urlconfigs = [
    {"name":"Appannie","url":"https://www.appannie.com/apps/google-play/app/#package/details/"},
    {"name":"Apkpure","url":"https://apkpure.net/cn/#package"},
    {"name":"ApkCombo","url":"https://apkcombo.com/#package"},
    {"name":"AppBrain","url":"https://www.appbrain.com/app/#package"},
    {"name":"SimilarWeb","url":"https://www.similarweb.com/app/google-play/#package/statistics"},
    {"name":"Appsflyer","url":"https://hq1.appsflyer.com/dashboard/overview/#package"},
    {"name":"AddMonitor","url":"http://www.hauyu.xyz/monitor/add_package/#package/"},
    {"name":"GenerateSpread","url":"http://www.hauyu.xyz/monitor/generate_spread/#package/"}
];
var curTab = null;

var isJson = function(obj){
    var isjson = typeof(obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
    return isjson;
}
/*
*使用JS跨域的方案，向服务器请求数据
*/
function fetchData() {
    var script = document.createElement("script");
    var url = "https://gitee.com/taugin/browser_plugins/raw/master/code/googleplay/config.js";
    script.src = url;
    script.type = "text/javascript";
    var head = document.getElementsByTagName("head");
    if(head && head[0]) {
        head[0].appendChild(script);
    }
}

// 回调配置数据
function config(data) {
    if (data != null && isJson(data)) {
        urlconfigs = data.urlconfigs;
        if (urlconfigs != null && urlconfigs instanceof Array && urlconfigs.length > 0) {
            updatePopup();
        }
    }
}

// 更新弹出框
function updatePopup() {
    var item = null;
    document.body.innerHTML = "<h3 style='color:red'>GP分析网站</h3>";
    for (var index = 0; index < urlconfigs.length; index++) {
		url_item = urlconfigs[index]
        if (url_item != null) {
            item = document.createElement("h3");
            item.innerText = url_item.name
            item.url_prefix = url_item.url
            item.className="item";
            item.onclick = openAppUrl;
            document.body.appendChild(item);
        }
    }
}

// 替换当前播放地址
function openAppUrl(event) {
    var prefix = this.url_prefix;
    if (curTab != null) {
        openUrl(prefix, getPackageName(curTab.url));
    }
    window.close();
}

function openUrl(prefix, packagename) {
    var appUrl = prefix.replace("#package", packagename)
    if (appUrl.indexOf("hauyu.xyz") >= 0 || appUrl.indexOf("127.0.0.1") >= 0) {
        curUrl = curTab.url
        if (curUrl.indexOf("app.diandian.com") >= 0 && curUrl.indexOf("googleplay?") >= 0 && curUrl.indexOf("id=") >= 0) {
            appUrl = appUrl + "?dd_url=" + encodeURIComponent(curTab.url)
        }
        var index = curTab.index + 1
        // chrome.tabs.create({"active":true, "index":index, "url":appUrl});
        sendAddPackageMessage(appUrl)
    } else {
        var index = curTab.index + 1
        chrome.tabs.create({"active":true, "index":index, "url":appUrl});
    }
}

function sendAddPackageMessage(appUrl) {
    chrome.runtime.sendMessage({url: appUrl, tabId : curTab.id}, function(response) {
        console.log(response);
     });
}

function getPackageName(url) {
	return getQueryParams(url, "id")
}

function getQueryParams(url, key) {
    map = {};
    try {
        var params = url.split("?")[1];
        var keyvalue = params.split("&");
        for (var index = 0; index < keyvalue.length; index++) {
            var tmp = keyvalue[index].split("=");
            try{
                map[tmp[0]] = tmp[1];
            }catch(e){
            }
        }
    } catch(e){
        console.log("e : " + e);
    }
    return map[key];
}

chrome.tabs.query({"active":true}, function(tab) {
    curTab = tab[0]
});

window.onload = function() {
    updatePopup();
    // 通过JSONP方式获取配置信息
    // fetchData();
};